/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: DynamicDataSourceConfig.java</p>
 *
 * @author zz
 * @date 2024/2/4
 * @version 1.0
 * History:
 * v1.0.0 2024/2/4 Create
 */
package com.sqlweb.sqlweb.config;

import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: DynamicDataSourceConfig</p>
 * <p>Description: </p>
 *
 * @author zz
 */
@Configuration
public class DynamicDataSourceConfig {

    private final Map<Object, Object> dataSources = new HashMap<>();

    @Primary
    @Bean
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 指定默认数据源
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource());
        // 配置多数据源
        Map<Object, Object> dataSourceMap = new HashMap<>(16);
        dataSourceMap.put("h2", defaultDataSource());
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        // 通过调用afterPropertiesSet确保所有属性设置后才初始化
        dynamicDataSource.afterPropertiesSet();
        return dynamicDataSource;
    }

    /**
     * 默认数据源配置
     */
    @Bean
    public DataSource defaultDataSource() {
        return DataSourceBuilder.create()
                .driverClassName("org.h2.Driver")
                .url("jdbc:h2:file:D:/data/demo_db")
                .username("admin")
                .password("admin")
                .build();
    }

    public void addDataSource(Integer key, DataSource dataSource) {
        dataSources.put(key, dataSource);
        // 更新已经配置的动态数据源
        DynamicDataSource dynamicDataSource = (DynamicDataSource) dynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSources);
        // 重新初始化动态数据源
        dynamicDataSource.afterPropertiesSet();
    }

    public void removeDataSource(Integer key) {
        dataSources.remove(key);
        // 更新已经配置的动态数据源
        DynamicDataSource dynamicDataSource = (DynamicDataSource) dynamicDataSource();
        dynamicDataSource.setTargetDataSources(dataSources);
        // 重新初始化动态数据源
        dynamicDataSource.afterPropertiesSet();
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dynamicDataSource) {
        return new JdbcTemplate(dynamicDataSource);
    }
}
